<?php defined('SYSPATH') or die('No direct access allowed.');

class OpenLogin_Wechat extends OpenLogin
{
    private $_openid = '';
    public function get_login_url($type="TOURIST")
    {
        $params['appid']         = $this->_app_key;
        $params['redirect_uri']  = $this->_callback_url.'?type='.$type;
        $params['state']         = $this->state();
        $params['scope']         = "snsapi_login";
        $params['response_type'] = "code";
        $wbaurl = "https://open.weixin.qq.com/connect/qrconnect";
        return $wbaurl . "?" . http_build_query($params);
    }

    public function get_access_token()
    {
        $code = (empty($_REQUEST['code']) ? '' : $_REQUEST['code']);
        $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$this->_app_key.'&secret='.$this->_app_secret.'&code='.$code.'&grant_type=authorization_code';
        
        $html = file_get_contents($token_url);
        $info = json_decode($html, true);
        $this->_openid = Arr::get($info, 'openid');
        return Arr::get($info, 'access_token');
    }
    
    public function get_openid($access_token)
    {
        return $this->_openid;
    }

    public function get_user_info($openid, $access_token)
    {
        $wb_graph_url = "https://api.weixin.qq.com/sns/userinfo?openid=" . $openid .
            "&access_token=" . $access_token;
        
        $wb_str = file_get_contents($wb_graph_url);

        $user = json_decode($wb_str, true);
        if (empty($user)) return false;
        if (!empty($user['error'])) return false;
        $info['uid']     = $openid;
        $info['userToken']  = $access_token;
        $info['gender']     = $user['sex'] == '1' ? '男' : '女';
        $info['nickname']   = $user['nickname'];
        $info['header_url'] = $user['headimgurl'];
        return $info;
    }
}
